package crawler.web.engine;

import java.io.File;
import java.io.FileNotFoundException;

import library.Tracer;

import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

import crawler.web.beans.CrawlURL;

/**
 * 负责berkeleydb的 调用
 * 
 * @author waynechen Feb 7, 2012 9:03:08 AM
 */
public abstract class AbstractFrontier implements Frontier {
	protected Environment env;
	protected static final String CLASS_CATALOG = "java_class_catalog";
	protected StoredClassCatalog javaCatalog;
	protected Database catalogDatabase;
	protected Database database;

	public AbstractFrontier(String homeDirectory) throws DatabaseException, FileNotFoundException {
		File file = new File(homeDirectory);
		file.mkdirs();
		//打开env
		Tracer.info("Opening environment in: " + homeDirectory);
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setTransactional(true);
		envConfig.setAllowCreate(true);
		env = new Environment(new File(homeDirectory), envConfig);
		//设置DatabaseConfig
		DatabaseConfig dbConfig = new DatabaseConfig();
		dbConfig.setTransactional(true);
		dbConfig.setAllowCreate(true);
		//打开
		catalogDatabase = env.openDatabase(null, CLASS_CATALOG, dbConfig);
		javaCatalog = new StoredClassCatalog(catalogDatabase);
		//设置Databaseconfig
		DatabaseConfig dbConfig0 = new DatabaseConfig();
		dbConfig0.setTransactional(true);
		dbConfig0.setAllowCreate(true);
		//打开
		database = env.openDatabase(null, "URL", dbConfig0);

		//		Runtime.getRuntime().addShutdownHook(new Thread() {
		//			@Override
		//			public void run() {
		//				close();
		//			}
		//		});
	}

	//关闭数据库,关闭环境
	public void close() throws DatabaseException {
		database.close();
		//catalogDatabase.close();不能关闭
		javaCatalog.close();
		env.cleanLog();
		env.close();
	}

	//put方法
	public abstract void put(String key, CrawlURL value);

	//get方法
	public abstract Object get(String key);

	//delete方法
	public abstract Object delete(String key);
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//